<template>
  <div class="max-table">
    <a-row class="button-group">
      <a-col :span="12">
        <a-button type="primary" @click="tableSearch">
          <SearchOutlined/>
          查找
        </a-button>
        <a-button type="primary" @click="tableEdit">
          <EditOutlined/>
          编辑
        </a-button>
        <a-button type="primary" @click="tableBatch">
          <CloudUploadOutlined/>
          批量
        </a-button>
      </a-col>
      <a-col :span="12">
        <a-dropdown class="right">
          <template #overlay>
            <a-menu>
              <a-menu-item v-for="fileType in defaultSetting.fileTypes">
                <FileZipOutlined/>
                {{ fileType }}
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary">
            <DownloadOutlined/>
            下载
          </a-button>
        </a-dropdown>
        <a-dropdown class="right">
          <template #overlay>
            <a-menu>
              <a-menu-item v-for="column in allColumns">
                <a-checkbox v-model:checked="column.tableShow" @change="columnChange">{{ column.title }}</a-checkbox>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary">
            <AppstoreOutlined/>
            视图
          </a-button>
        </a-dropdown>
        <a-button type="primary"
                  @click="tableRefresh"
                  class="right">
          <ReloadOutlined/>
          刷新
        </a-button>
      </a-col>
    </a-row>
    <a-table class="table"
        :rowKey="defaultSetting.rowKey"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        :size="defaultSetting.tableSize"
        :bordered="defaultSetting.tableBordered"
        :scroll="defaultSetting.tableScroll"
        :rowClassName="rowClassName"
        :pagination="{
          total: parseInt(tableTotal),
          pageSizeOptions: defaultSetting.pageSizeOptions,
          hideOnSinglePage: defaultSetting.hideOnSinglePage
        }"
        :customRow="customRow"
        @change="tableChange">
    </a-table>
    <a-modal v-model:visible="findModal" title="数据查找" :footer="null">
      <a-form>
        <a-form-item>
          <a-button type="dashed" @click="addCondition">
            <PlusOutlined/>
            新增查询条件
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="dataModal" title="数据修改" :footer="null">
      <max-form ref="formObj"
                :formColumns="allColumns"
                :formRule="formRule"
                :formData="formData"
                @addData="addData"
                @editData="editData"></max-form>
      <a-row>
        <a-col :span="8">
          <a-button @click="onAdd" block>新增</a-button>
        </a-col>
        <a-col :span="8">
          <a-button type="primary" @click="onEdit"
                    :disabled="disabled" block>修改
          </a-button>
        </a-col>
        <a-col :span="8">
          <a-button type="primary" @click="onDelete"
                    :disabled="disabled" block danger>删除
          </a-button>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal v-model:visible="batchModal" title="数据修改" :footer="null">

    </a-modal>
  </div>
</template>

<script>
import {
  SearchOutlined,
  EditOutlined,
  CloudUploadOutlined,
  ReloadOutlined,
  AppstoreOutlined,
  DownloadOutlined,
  FileZipOutlined,
  PlusOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue';
import {defineComponent, ref, reactive, toRaw, createVNode, nextTick} from 'vue';
import {Modal} from 'ant-design-vue';
import {dragable} from '../../utils/dragable.js';

export default defineComponent({
  name: 'maxTable',
  setup(props, context) {
    /**
     * 变量列表：
     * defaultSetting：组件默认配置
     * currentId：选中列主键
     * page：页码配置
     * columns：表格列数据
     * findModal：查找弹窗
     * dataModal：数据弹窗
     * batchModal：批量弹窗
     * formObj：表单对象
     * formData：表单数据
     * disabled：按钮禁止
     */
    const defaultSetting = ref({
      rowKey: 'id',
      tableSize: 'small',
      tableBordered: true,
      tableScroll: {},
      pageSizeOptions: ["10", "50", "100"],
      hideOnSinglePage: false,
      showLessItems: false,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      fileTypes: ['xlsx']
    });
    const currentId = ref('');
    const page = {current: 1, pageSize: 10};
    const columns = reactive([]);
    const findModal = ref(false);
    const dataModal = ref(false);
    const batchModal = ref(false);
    const formObj = ref();
    const formData = ref({});
    const disabled = ref(true);
    /**
     * 方法列表：
     * customRow：表格行事件
     * rowClassName：表格行样式选择
     * tableChange：表格页码切换
     * tableSearch：查找表格数据
     * tableEdit：修改表格数据
     * tableBatch：表格批量操作
     * tableRefresh：表格数据刷新
     * columnChange：表格列改变
     * addCondition：增加条件项
     * onAdd：新增事件
     * onEdit：修改事件
     * onDelete：删除事件
     * addData：新增数据
     * editData：修改数据
     */
    const customRow = (record, index) => {
      return {
        onClick: (event) => {
          currentId.value = record.id;
        }
      }
    };
    const rowClassName = (record, index) => {
      if (record.id === currentId.value) return 'current-row';
      return null;
    };
    const tableChange = (pagination, filters, sorter, {currentDataSource}) => {
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;
      tableRefresh();
    };
    const tableSearch = () => {
      findModal.value = true;
      nextTick(() => {
        dragable();
      });
    }
    const tableEdit = () => {
      disabled.value = true;
      formData.value = props.formDefaultData;
      if (currentId.value) {
        let current = props.tableData.find(data => data.id === currentId.value);
        if (current) {
          disabled.value = false;
          let obj = Object.assign({}, props.formDefaultData, current);
          if (props.beforeDataModal) {
            formData.value = props.beforeDataModal(obj);
          } else {
            formData.value = obj;
          }
        }
      }
      dataModal.value = true;
      nextTick(() => {
        dragable();
      });
    }
    const tableBatch = () => {
      batchModal.value = true;
      nextTick(() => {
        dragable();
      });
    }
    const tableRefresh = () => {
      context.emit('getData', page);
    };
    const columnChange = () => {
      columns.length = 0;
      columns.push(...props.allColumns.filter(column => column.tableShow === true));
    }
    const addCondition = () => {
    }
    const onAdd = () => {
      formObj.value.formValidate('addData');
    }
    const onEdit = () => {
      formObj.value.formValidate('editData');
    }
    const onDelete = () => {
      if (!props.beforeDelete || props.beforeDelete(formData.value)) {
        Modal.confirm({
          title: '确定删除该条数据？',
          icon: createVNode(ExclamationCircleOutlined),
          content: '请仔细核对主键编号：' + formData.value.id,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            context.emit('deleteData', formData.value);
            dataModal.value = false;
            tableRefresh();
          },
        });
      }
    }
    const addData = () => {
      if (!props.beforeAdd || props.beforeAdd(formData.value)) {
        context.emit('addData', formData.value);
        dataModal.value = false;
        tableRefresh();
      }
    }
    const editData = () => {
      if (!props.beforeEdit || props.beforeEdit(formData.value)) {
        context.emit('editData', formData.value);
        dataModal.value = false;
        tableRefresh();
      }
    }
    /**
     * 初始化
     */
    columnChange();
    tableRefresh();

    return {
      defaultSetting,
      columns,
      findModal,
      dataModal,
      batchModal,
      formObj,
      formData,
      disabled,
      customRow,
      rowClassName,
      tableChange,
      tableSearch,
      tableEdit,
      tableBatch,
      tableRefresh,
      columnChange,
      addCondition,
      onAdd,
      onEdit,
      onDelete,
      addData,
      editData
    };
  },
  components: {
    SearchOutlined,
    EditOutlined,
    CloudUploadOutlined,
    ReloadOutlined,
    AppstoreOutlined,
    DownloadOutlined,
    FileZipOutlined,
    PlusOutlined
  },
  props: {
    tableLoading: {
      type: Boolean,
      default: false
    },
    allColumns: {
      type: Array,
      default: []
    },
    tableData: {
      type: Array,
      default: []
    },
    tableTotal: {
      type: String,
      default: '-1'
    },
    setting: {
      type: Object,
      default: {}
    },
    formDefaultData: {
      type: Object,
      default: {}
    },
    formRule: {
      type: Object,
      default: {}
    },
    beforeDataModal: {
      type: Function
    },
    beforeAdd: {
      type: Function
    },
    beforeEdit: {
      type: Function
    },
    beforeDelete: {
      type: Function
    }
  }
});
</script>

<style scoped>
.max-table {
  min-width: 524px;
}

.button-group {
  padding-bottom: 12px;
}

.right {
  float: right;
}

.table{
  border: 1px solid #f0f0f0;
}

:deep(.ant-table-content) {
  height: 432px;
}

:deep(.ant-table-placeholder) {
  height: 380px;
}

:deep(.current-row) {
  background-color: #e6f7ff;
}
</style>